<?php
namespace Manage\Controller;
use \Pinyin;

class GameController extends CommonController {

    private $api;
    private $user;

    protected function _initialize(){
        $login = A('Login');
        if( ! session($login::SESSION_NAME) ) $this->error('请先登录', U('Login/Index'));
        $this->api = A('Api/Request');
        $this->user = session($login::SESSION_NAME);
    }


    /**
     * 游戏分类
     */
    public function Category(){
        $do = I('get.do');
        switch($do) {
            case 'add':
                if( IS_POST ){
                    $this->_add();
                }else{
                    $id = I('get.id');
                    $pid = $id > 0 ? $id : 0;
                    if( $pid === 0  ){
                        $parent_name = '顶级分类';
                    }else{
                        $db = zyt_data_init();
                        $category = $db->getGameCategoryInfo($pid);
                        $parent_name = $category[0]['class_name'];
                    }
                    $this->assign('parent_name', $parent_name);
                    $this->assign('pid', $pid);
                    $this->display('Add');
                }
                break;
            case 'edit':
                if( IS_POST ){
                    $result = $this->_editCategory();
                    if( $result ){
                        $this->success('更新成功', U('Game/Category'));
                    }else{
                        $this->error('更新失败', U('Game/Category'));
                    }
                }else{
                    $id = I('get.id');
                    if(! $id)  $this->error('请选择游戏分类');

                    $db = zyt_data_init();
                    $category = $db->getGameCategoryInfo( $id )[0];
                    $pid      = $category['class_parent_id'];
                    $parent = $pid == 0 ? '顶级分类' : $db->getGameCategoryInfo($pid)[0]['class_name'];
                    $category['parent_name'] = $parent;
                    $this->assign('category', $category);
                    $this->display('Edit');
                }

                break;

            case 'sort':
                $this->_sort();
                break;

            case 'deleteAll':
                $this->_delCategorySelected();
                break;
            case 'delete':
                $this->_delCategory();
                break;
            default:
                $db = zyt_data_init();
                $category = $db->getGameCategory();
                $vlist = $this->_list($category, 0);
                //dump($vlist);
                if( !empty($vlist) ){
                    $this->assign('vlist', $vlist);
                }
                $this->display('Index');
                break;
        }
    }

    /**
     * 游戏列表
     */
    public function Lists(){
        $do = I('get.do');
        switch($do) {
            case 'addGame':
                $db = zyt_data_init();
                $category = $db->getGameCategory();
                $gamefl = array();
                foreach( $category as $cate ){
                    if($cate['class_parent_id'] == 0){
                        $gamefl[] = $cate;
                    }
                }
                $this->assign('gamefl',$gamefl);
                if( IS_POST ){
                    $this->_addGame();
                } else {
                    $db = zyt_data_init();
                    $recharge = $db->getGameRechargeList();

                    $this->assign('recharge_list', $recharge);
                    $this->display('addList');
                }
                break;

            case 'edit':
                if( IS_POST ){
                    $id = I('post.game_id');
                    if( ! $id ) $this->error('游戏不存在', U('Game/Lists'));
                    $result = $this->_edit( $id );
                    if($result){
                        $this->success('更新成功', U('Game/Lists'));
                    }else{
                        $this->error('更新失败');
                    }
                }else{
                    $id = (int)I('get.id');
                    if( $id <= 0  ) exit();
                    if( ! $id ) $this->error('请选择要编辑的游戏');

                    $db = zyt_data_init();
                    $game = $db->getGameInfo($id)[0];
                    $category = $db->getGameCategory();
                    $servers  = $db->getGameServer($id);
                    $currency = sliceGameRate($game['game_ratio_desc']);

                    $game['currency'] = $currency['currency'];
                    $game['ratio']    = $currency['ratio'];

                    $gamefl = array();
                    $gamefl2 = array();
                    foreach( $category as $cate ){
                        if($cate['class_parent_id'] == 0){
                            $gamefl[] = $cate;
                        }
                        if($cate['class_parent_id'] == $game['class_parent_id']){
                            $gamefl2[]  = $cate;
                        }
                    }

                    $recharge = $db->getGameRechargeList();

                    $this->assign('recharge_list', $recharge);

                    $this->assign('gamefl',$gamefl);
                    $this->assign('gamefl2',$gamefl2);
                    $this->assign('game', $game);
                    $this->assign('servers', $servers);
                    $this->display('addList');
                }

                break;

            case 'move':
                $this->_move();
                break;

            case 'delete':
                $this->_delGame();
                break;
            case 'selectlist':
                $this->_selectlist();
                break;
            case 'Search':
                $get = I('get.');
                $keyword = $get['keyword'];
                $cid     = $get['cid'];

                if(empty($keyword)){
                    $keyword = null;
                }

                if(empty($cid)){
                    $cid = null;
                }

                $list = $this->_search($keyword, $cid);

                $db = zyt_data_init();
                $category = $db->getGameCategory();

                $gamefl  = array();
                $gamefl2 = array();
                $parent_id   = null;
                $children_id = $cid;

                foreach($category as $cate){
                    if( $cate['class_parent_id'] == 0 ){
                        $gamefl[] = $cate;
                    }
                    if( $cate['class_id'] == $cid ){
                        $parent_id = $cate['class_parent_id'];
                    }

                }
                foreach($category as $cate){
                    if($cate['class_parent_id'] == $parent_id){
                        $gamefl2[] = $cate;
                    }
                }

                $this->assign('gamefl',$gamefl);
                $this->assign('gamefl2' , $gamefl2);
                $this->assign('children_id' , $children_id);
                $this->assign('parent_id' , $parent_id);


                $total = count($list);
                $nowpage = (int)I('get.page');
                $page = $nowpage > 0 ? $nowpage : 1;
                $pagesize = C('LIST_PAGE_SIZE');

                $list = $this->_page($list, $page, $pagesize);

                $this->assign('pagesize', $pagesize);
                $this->assign('pages', ceil($total/$pagesize));
                $this->assign('total', $total);


                $this->assign('vlist', $list);
                $this->display('GameList');
                break;
            default:
                $db = zyt_data_init();
                $category = $db->getGameCategory();
                $gamefl = array();

                foreach( $category as $cate ){
                    if($cate['class_parent_id'] == 0){
                        $gamefl[] = $cate;
                    }
                }

                $this->assign('gamefl',$gamefl);
                $list = $this->_listgame();

                $total = count($list);
                $nowpage = (int)I('get.page');
                $page = $nowpage > 0 ? $nowpage : 1;
                $pagesize = C('LIST_PAGE_SIZE');

                $list = $this->_page($list, $page, $pagesize);

                $this->assign('pagesize', $pagesize);
                $this->assign('pages', ceil($total/$pagesize));
                $this->assign('total', $total);

                $this->assign('vlist', $list);
                $this->display('GameList');
                break;
        }
    }

    //返回数组分页数据
    private function _page($data, $page, $pagesize){
        $page     = (int)$page;
        $pagesize = (int)$pagesize;
        if(empty($data) || !is_array($data) || $page <= 0 || $pagesize <= 0) return [];
        $result = array();

        $start = ($page - 1) * $pagesize;
        $end   = $start + $pagesize - 1;
        $index = range($start, $end);

        foreach($index as $i){
            if( isset($data[$i]) ){
                $result[] = $data[$i];
            }else{
                break;
            }
        }
        return $result;
    }

    private function _list($category, $pid){
        static $tmp = array();
        static $deep = 0;
        foreach( $category as $k=>$v ){
            if( $v['class_parent_id'] == $pid ){
                $html = '';
                if( $pid == 0 ){
                    $deep = 0;
                }
                for($i=0; $i<$deep; $i++){
                    $html .= '&nbsp;&nbsp;&nbsp;├─';
                }
                $v['html'] = $html;
                $tmp[] = $v;
                $deep ++;
                $this->_list($category, $v['class_id']);
            }
        }

        $deep --;

        $result = $tmp;
        unset($tmp);
        unset($deep);
        return $result;
    }

    //更新分类排序
    private function _sort(){
        $post = I('post.');
        $sorts = $post['sort'];
        $cid = $post['class_id'];

        if(empty($cid)) {
            $this->error('请选择要更新排序的分类');
        }

        $sql = 'UPDATE [sso_game_class] SET [class_sort] = CASE class_id ';
        foreach( $cid as $id ){
            $sort = (int)$sorts[$id];
            if( $sort >= 0 ){
                $sql .= ' WHEN ' . $id . ' THEN ' . $sort;
            }
        }
        $in = implode(',', $cid);
        $sql .= ' END WHERE class_id IN (' . $in .')';

        $db = zyt_data_init();
        $result = $db->query($sql);

        if( $result->rowCount() > 0 ){
            $this->success('更新成功');
        }else{
            $this->error('更新失败', U('Game/Category'));
        }
    }

    private function _delCategory(){
        $id = (int)I('get.id');
        if( ! $id > 0 )   $this->error('非法操作');
        $db = zyt_data_init();
        $result = $db->deleteCategoryById($id);
        $result['output'][0] == 1 ? $this->success('删除成功') : $this->error('删除失败');
    }

    private function _add(){
        $post = I('post.');

        $class_parent_id = trim($post['pid']);
        $class_name = trim($post['column_name']);
        $class_user_add = 58;
        $class_sort = trim($post['column_sort']);

        if( $class_parent_id === '' ) $this->error('数据出错');
        if( $class_name === '' ) $this->error('请输入分类名称');
        if( $class_sort === '' ) $this->error('数据出错');

        $db = zyt_data_init();
        $result = $db->addGameCategory($class_parent_id, $class_name, $class_user_add, $class_sort);
        $result['output'][0] === 1 ? $this->success('添加成功', U('Game/Category')) : $this->error('添加失败', U('Game/Category'));
    }

    private function _editCategory(){
        $post = I('post.');
        $cid = $post['cid'];
        if( ! $cid )  $this->error('该游戏分类不存在');

        $title = $post['column_name'];
        $pid   = $post['pid'];
        $sort  = $post['column_sort'];
        $uid   = 58;

        $db = zyt_data_init();
        $result = $db->updateGameCategory($cid, $title, $pid, $sort, $uid);
        return $result['output'][0];
    }

    private function _edit($id){
        $post = I('post.');

        $title = trim( $post['game_name'] );
        $initials = trim( $post['initial'] );
        $recharge = trim( $post['recharge'] );
        $category = trim( $post['cid'] );
        $currency = trim( $post['currency'] );
        $ratio    = trim( $post['ratio'] );

        if( empty($category) )  $this->error('请选择游戏分类');

        $db = zyt_data_init();

        if( $recharge == 0 ){
            $is_recharge = 0;
            $recharge    = 0;
        }else{
            $is_recharge = 1;
        }

        $uid = 58;
        $db->startTrans();
        $map['game_id'] = $id;
        $data['game_name'] = $title;
        $data['game_name_initials'] = $initials;
        $data['game_recharge_class'] = $recharge;
        $data['game_is_recharge'] = $is_recharge;
        $data['game_class_id'] = $category;
        $data['game_belongto_user_id'] = $uid;
        $data['game_ratio_desc'] = $currency . ','.$ratio;
        $db->table('game')->where($map)->save($data);
        //更新区服表
        $servers = $post['servers'];
        if( ! empty($servers)  ){
            $db->addGameServer($id, $servers);
        }
        $result = $db->commit();
        return $result;
    }

    private function _search($keyword, $cid){
        $db = zyt_data_init();
        return $db->searchGame($keyword, $cid);
    }

    private function _listgame(){
        $db = zyt_data_init();
        $list = $db->getGameList();
        return $list;
    }
    private function _addGame(){
        $post = I('post.');

        $game_name = trim($post['game_name']);
        $game_class_id = trim($post['cid']);
        $initial = trim($post['initial']);
        $recharge = trim($post['recharge']);
        $currency = trim($post['currency']);
        $ratio = trim($post['ratio']);
        $game_user_add = 58;

        if( $game_name === '' ) $this->error('请输入名字');
        if( $game_class_id === '' ) $this->error('请选择分类');
        if( $initial === '' ) $this->error('请输入字母索引');
        if( $recharge === '' ) $this->error('请选择游戏充值类型');
        $db = zyt_data_init();
        if( $recharge == 0 ){
            $is_recharge = 0;
            $recharge    = 0;
        }else{
            $is_recharge = 1;
        }
        $db->startTrans();
        $data['game_class_id'] = $game_class_id;
        $data['game_name']     = $game_name;
        $data['game_is_disable'] = 0;
        $data['game_is_recharge'] = $is_recharge;
        $data['game_name_initials'] = $initial;
        $data['game_belongto_user_id'] = $game_user_add;
        $data['game_recharge_class'] = $recharge;
        $data['game_user_add'] = $game_user_add;
        $data['game_time_add'] = time();
        $data['game_user_update'] = $game_user_add;
        $data['game_time_update'] = time();
        $data['game_ratio_desc'] = $currency . ',' . $ratio;
        $db->table('game')->add($data);
        $gid = $db->getLastInsertId();
        //添加游戏区服
        if(! empty($post['servers'])){
            $sql = 'INSERT INTO sso_game_server (game_server_name, game_id) values';
            foreach( $post['servers'] as $v ){
                $sql .= "('$v', $gid) ,";
            }
            $sql = substr($sql, 0, -1);
            $db->query($sql);
        }
        $result = $db->commit();
        $result ? $this->success('添加成功', U('Game/Lists')) : $this->error('添加失败', U('Game/Lists'));
    }
    public function fistName(){
        //取首字母
        import('Org.Util.Pinyin');
        $Pinyin = new Pinyin();
        $name=I('post.name');
        $str=$Pinyin::encode("$name",1,2);
        echo strtoupper(substr($str,0,1));
    }
    private function _delGame(){
        $gid = (int)I('get.id');
        if( ! $gid > 0 ) $this->error('非法操作');
        $db = zyt_data_init();
        $result = $db->deleteGameById($gid);
        $result['output'][0] == 1 ? $this->success('删除成功') : $this->error('删除失败');
    }


    private function _selectlist(){//下拉列表
        if(isset($_POST['list1'])){
            $game_class_id=$_POST['list1'];
        }else{
            $game_class_id=$_POST['list2'];
        }

        $db = zyt_data_init();
        $category = $db->getGameCategory();
        $gamefl = array();
        foreach( $category as $cate ){
            if( $cate['class_parent_id'] == $game_class_id){
                $gamefl[] = $cate;
            }
        }
        header('Content-type: application/json');
        exit( json_encode($gamefl));
    }
}